package com.example.springboot.file.controller;

import com.example.springboot.file.constant.FileTypeEnum;
import com.example.springboot.file.entity.FileDatalVo;
import com.example.springboot.file.util.FTPHelper;
import com.example.springboot.file.util.FTPUtil;
import com.example.springboot.file.util.FileUtil;
import com.example.springboot.file.util.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 使用ftp方式获取文件流
 */
@Controller
@RequestMapping("/ftpClient")
public class FtpClientAction {
    private static final Log log = LogFactory.getLog(FtpClientAction.class);
//    @Autowired
//    private FtpClientService ftpClientService;

    @Value("${ftpHost}")
    private String ftpHost = "127.0.0.1";
    @Value("${ftpPort}")
    private int ftpPort = 21;
    @Value("${userName}")
    private String userName = "root";
    @Value("${password}")
    private String password = "123456";
    private String root_path = "/upload";

    /**
     * @param files
     * @param systemType：系统类型（1-基础业务子系统；2-指挥调度子系统；3-前端管理子系统；4-实战应用子系统；5-网吧子系统；6-系统运维子系统；7-其他）
     * @return
     */
    @RequestMapping("/upload.action")
    @ResponseBody
    public List<FileDatalVo> saveAttachements(@RequestParam("files") MultipartFile[] files, String systemType) {

        List<FileDatalVo> list = this.saveAttachement(files, systemType);
        return list;
    }

    /**
     * @param files
     * @param systemType：系统类型（1-基础业务子系统；2-指挥调度子系统；3-前端管理子系统；4-实战应用子系统；5-网吧子系统；6-系统运维子系统；7-其他）
     * @return
     */
    public List<FileDatalVo> saveAttachement(MultipartFile[] files, String systemType) {

        List<FileDatalVo> list = new ArrayList<FileDatalVo>();
        if (null == files || files.length <= 0)
            return list;

        //文件真实路径
        String remotePath = FileTypeEnum.toEnum(systemType).getValue() + File.separator;
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                String subfix = FileUtil.getFileSubfix(fileName);
                String fileName2 = UUIDUtils.newGUID() + subfix;
                try {
                    Date date = new Date();
                    String path = root_path + File.separator + date.getYear() + File.separator + date.getMonth();
                    FTPUtil.uploadFile(ftpHost, ftpPort, userName, password, path, fileName2, file.getInputStream());
                    log.debug("文件 [" + fileName2 + "] 已上传至 ftp: [" + remotePath + "] 文件夹中.");

                    FileDatalVo fileDetailVo = new FileDatalVo();
                    fileDetailVo.setFileType(subfix);
                    fileDetailVo.setFilePath(path + File.separator + fileName2);
                    fileDetailVo.setFileName(fileName2);
                    fileDetailVo.setFileSize(file.getSize());
                    fileDetailVo.setMsg("上传成功");
                    fileDetailVo.setStatus(true);
                    list.add(fileDetailVo);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * downloadFile(文件下载)
     */
    @RequestMapping("/downloadFile.action")
    public String downloadFile(String fileName, String filePath, HttpServletResponse response) {
        try {
            if (StringUtils.isNotBlank(fileName)) {
                response.setContentType(FileUtil.getContentType(fileName));
                //tomcat
                //response.setHeader("Content-Disposition", "attachment;" + " filename=" + realName);
                //weblogic
                response.setHeader("Content-Disposition", "attachment;" + " filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            ServletOutputStream os = response.getOutputStream();
            FTPHelper.downloadFile(filePath, fileName, os);
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除附件
     */
    @RequestMapping(value = "/deleteFile.action")
    @ResponseBody
    public String deleteFile(HttpServletRequest request, String filePath, String fileName) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //删除关联关系
            FTPHelper.deleteFileToFTPUnlock(filePath, fileName);
            map.put("flag", 0);
        } catch (Exception e) {
            map.put("flag", 1);
            e.printStackTrace();
        }
        String json = map.toString();
        return json;
    }

}